<?php

namespace app\index\service;

use app\common\ConfigBase;
use app\common\model\ToolModel;
use app\index\model\UserModel;
use app\index\model\OldproductmanageModel;
use app\index\model\NewproductauditModel;
use think\Db;

class OldproductmanageService
{

    /**
     * 老品列表/导出
     * @author LSH
     * @return array
     */
    public static function getOldProductAssignList($param){

        $titles=[
            'sku'=>'SKU',
            'spu'=>'SPU',
            'name'=>'采购名称',
            'proposer'=>'申请人员',
            'assign_time'=>'分派时间',
            'finish_time'=>'完成时间',
            'manufacture_status'=>'制作状态',
            'audit_remarks'=>'制作备注'
        ];

        if($param['type'] == 'edit'){
            $titles['grade']='描述等级';
            $titles['demand_sector']='需求部门';
            $titles['manufacture_type']='制作类型';
            $titles['import_operator']='导入人员';
            $titles['operator']='编辑人员';
        }else if($param['type'] == 'img'){
            $titles['quantity']='销售数量/单位';
            $titles['logo']='品牌Logo';
            $titles['grade']='图片等级';
            $titles['manufacture_type']='交接类型';
            $titles['operator']='图片人员';
        }

        return NewproductauditModel::dbGetEditImgAuditList($param, $titles, "\app\index\service\OldproductmanageService::getOldProductAssignLogic");
    }

    /**
     * 老品 图片/描述列表数据逻辑
     * @author LSH
     * @return array
     */
    public static function getOldProductAssignLogic($data){
        $proposer = array_column($data, 'proposer'); //图片申请人员 / 编辑申请人员
        $operator = array_column($data, 'operator'); //图片人员 / 编辑人员
        $import_operator = array_column($data, 'import_operator'); //导入人员
        $user_id = array_filter(array_merge($proposer,$operator,$import_operator));

        $user = UserModel::getUserById($user_id);
        foreach ($data as &$val) {
            $val['quantity'] = $val['quantity'].$val['quantity_unit'];
            $val['proposer'] = $user[$val['proposer']]??'';
            $val['operator'] = $user[$val['operator']]??'';
            $val['import_operator'] = $user[$val['import_operator']]??'';
            $val['skuinfo'] = 'SKU：'.$val['sku'].'<br/>SPU：'.$val['spu'].'<br/>采购名称：'.$val['name'];
            if(isset($val['demand_sector'])){
                $val['editdatainfo'] = '描述等级：'.$val['grade'].'<br/>需求部门：'.$val['demand_sector'].'<br/>制作类型：'.$val['manufacture_type'];
            }
            $val['editstaffinfo'] = '导入人员：'.$val['import_operator'].'<br/>申请人员：'.$val['proposer'].'<br/>编辑人员：'.$val['operator'];
            $val['edittimeinfo'] = '分派时间：'.$val['assign_time'].'<br/>完成时间：'.$val['finish_time'];
            $val['imgdatainfo'] = '销售数量/单位：'.$val['quantity'].'<br/>品牌Logo：'.$val['logo'];
            $val['imgmakeinfo'] = '图片等级：'.$val['grade'].'<br/>交接类型：'.$val['manufacture_type'];
            $val['imgstaffinfo'] = '申请人员：'.$val['proposer'].'<br/>图片人员：'.$val['operator'];
            $val['timeinfo'] = '确定时间：'.$val['assign_time'].'<br/>完成时间：'.$val['finish_time'];
        }

        return $data;
    }

    /**
     * 编辑/图片 任务导入
     * @author LSH
     * @return arrayupdateAffirmCancelAudit
     */
    public static function uploadEditImgTaskListInfo($datas, $param)
    {
        $error = [];
        if($param['type'] == 'edit'){
            $table = 'manage_edit_audit';
            $import_operator = array_column($datas, '4'); //导入人员
            $fields = ['sku','grade','demand_sector','manufacture_type','proposer','audit_remarks'];
            $namef = ['sku','描述等级','需求部门','制作类型','申请人员','制作备注'];
        }else if($param['type'] == 'img'){
            $table = 'manage_img_audit';
            $import_operator = array_column($datas, '3'); //导入人员
            $fields = ['sku','grade','manufacture_type','proposer','audit_remarks'];
            $namef = ['sku','图片等级','交接类型','申请人员','制作备注'];
        }


        $exist = ToolModel::select($table, ['manufacture_status'=>['<',5],'cancel'=>0], 'sku,id','','sku');
        $in_skus = ToolModel::select('skus', ['sku'=>['IN',array_column($datas, '0')]], 'sku,id','','sku');
        $editor = ToolModel::select('setting_editor', ['sku'=>['IN',array_column($datas, '0')]], 'sku,img_operator,edit_operator','','sku');

        $user = array_filter($import_operator);
        $userArr = UserModel::getUserByNike($user);

        $skus = [];
        $inData = [];
        foreach ($datas as $k => $v) {
            $mark = false;

            if(empty($v[0])){
                $error[] = "SKU参数缺失";
                continue;
            }

            if(!isset($in_skus[$v[0]])){
                $error[] = "SKU: {$v[0]} 不存在。";
                continue;
            }

            if(in_array($v[0], $skus)){
                $error[] = "SKU: {$v[0]} 导入数据重复。";
                continue;
            }

            if(isset($exist[$v[0]])){
                $error[] = "SKU: {$v[0]} 存在未完成任务。";
                continue;
            }

            $skus[] = $v[0];
            foreach ($fields as $key => $val) {
                if(empty(trim($v[$key]))){
                    $mark = true;
                    $error[] = "SKU: {$v[0]},{$namef[$key]}数据缺失!  ";
                    continue;
                }

                if($fields[$key] == 'proposer'){
                    if(!isset($userArr[$v[$key]])){
                        $mark = true;
                        $error[] = "SKU: {$v[0]},{$namef[$key]}不存在!  ";
                        continue;
                    }
                    $inData[$k][$fields[$key]] = $userArr[$v[$key]];
                }else{
                    $inData[$k][$fields[$key]] = $v[$key];
                }
            }

            $inData[$k]['import_operator'] = $param['uid'];
            $inData[$k]['operator'] = $editor[$v[0]][$param['type'].'_operator']??'';
            
            if($mark) continue;
        }
        unset($datas,$skus);
        //错误信息输出
        if (!empty($error)) {
            $msg=[];
            foreach ($error as $v3){
                $msg[]=['msg'=>$v3];
            }
            unset($error);
            return returnArr(2, '',$msg);
        }else{
            ToolModel::insertData($inData, $table);
            unset($inData);
        }

        //成功
        return returnArr();
    }

    /**
     * 编辑/图片 任务批量确认
     * @author LSH
     * @return array
     */
    public static function uploadEditImgBatchAffirm($datas, $param)
    {
        $sku = [];
        $error = [];
        $table = ($param['type'] == 'edit')?'manage_edit_audit':'manage_img_audit';
        $skus = ToolModel::select($table, ['manufacture_status'=>1,'sku'=>['IN',array_column($datas, '0')],'assign_id'=>0,'cancel'=>0], 'sku,id,operator','','sku');

        foreach ($datas as $v) {
            if(!isset($skus[$v[0]])){
                $error[] = "SKU: {$v[0]} 状态错误，核实后重新导入。";
                continue;
            }else if(empty($skus[$v[0]]['operator'])){
                $error[] = "SKU: {$v[0]} 未分派，请分派后再进行确定操作。";
                continue;
            }else{
                $sku[] = $v[0];
            }
        }

        //错误信息输出
        if (!empty($error)) {
            $msg=[];
            foreach ($error as $v3){
                $msg[]=['msg'=>$v3];
            }
            $code = (count($datas) == count($error))?2:4;
            unset($datas,$error,$skus);
            return returnArr($code, '',$msg);
        }else{
            ToolModel::updateData(['sku'=>['IN',$sku],'assign_id'=>0,'cancel'=>0,'manufacture_status'=>1],['manufacture_status'=>2,'assign_time'=>date('Y-m-d H:i:s',time())], $table);
        }
         unset($datas,$error,$skus);
        return returnArr(); //成功
    }

    /**
     * 编辑/图片 任务批量取消
     * @author LSH
     * @return array
     */
    public static function uploadEditImgBatchCancel($datas, $param)
    {
        $sku = [];
        $error = [];
        $table = ($param['type'] == 'edit')?'manage_edit_audit':'manage_img_audit';
        $skus = ToolModel::select($table, ['manufacture_status'=>['<',3],'sku'=>['IN',array_column($datas, '0')],'assign_id'=>0,'cancel'=>0], 'sku,id','','sku');

        foreach ($datas as $v) {
            if(!isset($skus[$v[0]])){
                $error[] = "SKU: {$v[0]} 状态错误，已制作不可取消，核实后重新导入。";
                continue;
            }else{
                $sku[] = $v[0];
            }
        }

        //错误信息输出
        if (!empty($error)) {
            $msg=[];
            foreach ($error as $v3){
                $msg[]=['msg'=>$v3];
            }
            unset($error);
            return returnArr(2, '',$msg);
        }else{
            ToolModel::updateData(['sku'=>['IN',$sku],'assign_id'=>0,'cancel'=>0,'manufacture_status'=>['<',3]],['cancel'=>1], $table);
        }
         unset($datas,$data,$skus);
        //成功
        return returnArr();
    }

    /**
     * 编辑/图片任务 确定/取消
     * @author LSH
     * @return array
     */
    public static function updateAffirmCancelAuditLogic($param)
    {
        $table = $param['type'] == 'edit'?'manage_edit_audit':'manage_img_audit';
        $data = ToolModel::find($table,['id'=>$param['id'],'sku'=>$param['sku'],'assign_id'=>0]);
        if(empty($data)){
            return returnJson(0,'数据不存在');
        }

        if($param['status'] == 'cancel'){
            if($data['cancel'] == 1){
                return returnJson(0,'该数据已取消，请勿重复操作！');
            }

            if($data['manufacture_status'] >= 3){
                return returnJson(0,'该数据状态为已制作，不可取消！');
            }
        }else{
            if($data['manufacture_status'] >= 2){
                return returnJson(0,'该数据已确定，请勿重复操作！');
            }

            if($data['operator'] == ''){
                return returnJson(0,'请先分派人员，再进行确认！');
            }
        }
        
        return OldproductmanageModel::dbUpdateAffirmCancelAudit($param);
    }
    //勾选批量确认
    public static function updateAffirmCancelAuditLogicCheck($param)
    {

        $table = $param['type'] == 'edit'?'manage_edit_audit':'manage_img_audit';

        $list = ToolModel::select($table,['id'=>['in',$param['id']],'assign_id'=>0]);
        if(empty($list)){
            return returnJson(0,'数据不存在');
        }
        foreach ($list as $data){
            if($param['status'] == 'cancel'){
                if($data['cancel'] == 1){
                    return returnJson(0,'该数据已取消，请勿重复操作！');
                }

                if($data['manufacture_status'] >= 3){
                    return returnJson(0,'该数据状态为已制作，不可取消！');
                }
            }else{
                if($data['manufacture_status'] >= 2){
                    return returnJson(0,'该数据已确定，请勿重复操作！');
                }

                if($data['operator'] == ''){
                    return returnJson(0,'请先分派人员，再进行确认！');
                }
            }
            $data1=[];
            if($param['status'] == 'cancel'){
                $data1['cancel'] = 1;
            }else{
                $data1['assign_time'] = date('Y-m-d H:i:s',time());
                $data1['manufacture_status'] = 2;
            }
           Db::table($table)->where(['id'=>$data['id'],'assign_id'=>0])->update($data1);
        }
        return returnJson();
    }

    /**
     * 老品 图片/描述列表数据逻辑
     * @author LSH
     * @return array
     */
    public static function updateAssignInfoLogic($param){
        if(empty($param['id'])){
            return returnJson(0,'参数错误');
        }
        $table = $param['type'] == 'img'?'manage_img_audit':'manage_edit_audit';
        $data = ToolModel::find($table, ['id'=>$param['id']]);

        if(empty($data) || $data['operator']){
            return returnJson(0,'数据不存在或已分派');
        }
        if(empty($data['sku'])){
            return returnJson(0,'参数缺失');
        }

        return OldproductmanageModel::dbUpdateAssignInfo($param,$data);
    }
    
}